<template>
  <div class="card card-flush shadow-lg">
    <div class="card-header pt-7">
      <h3 class="card-title align-items-start flex-column">
        <span class="card-label fw-bold text-gray-800">最近一个月活跃仓库Top10</span>
        <span class="fw-semibold fs-6 mt-1 text-gray-500">
          按提交行数排序，只统计有效提交（非merge，单次提交行数小于10000）
        </span>
      </h3>
      <div class="card-toolbar">
        <a href="#" class="btn btn-sm btn-light" @click="fetchData">刷新</a>
      </div>
    </div>
    <div class="card-body pt-6">
      <div v-if="loading" class="text-center">
        <div class="spinner-border" role="status">
          <span class="sr-only">加载中...</span>
        </div>
      </div>
      <div v-else-if="error" class="alert alert-danger">
        {{ error }}
      </div>
      <div v-else class="table-responsive h-425px h-lg-425px">
        <table
          class="table-row-dashed gs-0 gy-3 sticky-header sticky-footer my-0 table align-middle"
        >
          <thead>
            <tr class="fs-6 fw-bold border-bottom-0 text-gray-800">
              <th class="min-w-175px p-0 pb-3 text-start">仓库名称</th>
              <th class="min-w-100px p-0 pb-3 text-end">提交次数</th>
              <th class="min-w-100px p-0 pb-3 text-end">总变化行</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, i) in topData" :key="i">
              <td>
                <span class="fw-bold fs-3 text-gray-800">{{ item.name }}</span>
                <br />
                <span class="fw-semibold fs-6 text-gray-500">{{ item.pathWithNamespace }}</span>
              </td>
              <td class="fw-bold text-end">{{ item.commitCount }}</td>
              <td class="fw-bold text-end">{{ item.totalChanges }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { repositoryService } from '@/services/business/repository.service';
import type { TopRepository } from '@/types/business/repository';

const topData = ref<TopRepository[]>([]);
const loading = ref(true);
const error = ref<string | null>(null);

const fetchData = async () => {
  try {
    loading.value = true;
    error.value = null;
    topData.value = await repositoryService.getTopActiveRepositories();
  } catch (err) {
    console.error('Failed to fetch top repos last month:', err);
    error.value = '加载Top10活跃仓库失败，请稍后重试';
  } finally {
    loading.value = false;
  }
};

onMounted(fetchData);
</script>
